#!/bin/sh
#set -x

# VARIABLES
# TESTS (shitloads)
# BU FUNCTIONS
# MAIN

#----------------------------------------
# VARIABLES
#----------------------------------------
bu_disk="/media/disk"
bu_folder="$bu_disk"/backup
user_folder="/home/user"

user_folder_bu="$bu_folder"/"${user_folder##*/}".configs
etc_folder="/etc"
etc_folder_bu="$bu_folder"/etc

option="$1"

#----------------------------------------
# TESTS
#----------------------------------------
#if [ $(id -u) -ne 0 ]; then
#  printf "Run as root\n"
#  exit 1
#fi 

usage () {
	printf "   
	Usage: backup [options]
	 
	-h | --help  
	display help 

	-d | --default
	backup etc and user config files to a mounted stick/disk/sd
	edit variables: 
	backup_folder (mountpoint)
	home_folder (user who owns the configs)
  
	-f | --force 
	force to backup without a mounted disk/stick/sd/... 
	edit variables: 
	backup_folder (not mounted )
	home_folder (user who owns the configs)
	\n"
  
  exit 0
}


check_mount () {
  if !  mount | grep "$bu_disk"; then
    printf "%s not mounted\n" "$bu_disk"
    printf "mount it or edit the variable bu_disk\n"
    printf "use -f if you want to back up to the local disk"
    exit 1
  fi 
}


check_user () {
  if ! [ -d "$user_folder" ]; then 
    printf "%s doesn't exit\nEdit the variable: user_folder\n" "$user_folder"
    exit 1
  fi 
}


check_folders () {
  if ! [ -d "$bu_folder" ]; then
    mkdir "$bu_folder" || \
      { printf "mkdir %s failed\n" "$bu_folder"; exit 1; }
  fi 

  if ! [ -d "$user_folder_bu" ]; then
    mkdir "$user_folder_bu" || \
      { printf "mkdir %s failed\n" "$user_folder_bu"; exit 1; }
  fi 

  if ! [ -d "$etc_folder_bu" ]; then
    mkdir "$etc_folder_bu" || \
      { printf "mkdir %s failed\n" "$etc_folder_bu"; exit 1; }
  fi 
}


#----------------------------------------
# BU  FUNCTIONS
#----------------------------------------
bu_home_config () {
  rsync -auv --delete  "$user_folder"/.[!.]* "$user_folder_bu"
}

bu_etc () {
  rsync -auv --delete "$etc_folder" "$etc_folder_bu"
}


#----------------------------------------
# MAIN 
#----------------------------------------
while :; do
  case $option in 
    -h|--help) usage; exit 0;;
    -d|--default) check_mount; 
                  check_user;
		  check_folders;
		  bu_home_config;
		  bu_etc; 
		  break  ;;
    -f|--force) check_user;
      	        check_folders;
		bu_home_config;
		bu_etc;
		break;;
    *) usage; break;; 
esac
done 

